package com.epfresh.location;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.utils.DistanceUtil;
import com.epfresh.R;

import java.util.List;

/**
 * Created by imahe001 on 2015/9/29.
 */
public class PoiSearchAdapter extends BaseAdapter {

    private Context context;
    private List<PoiInfo> poiInfos;
    private LatLng locationLatLng;

    public PoiSearchAdapter(Context context, List<PoiInfo> poiInfos, LatLng locationLatLng) {
        this.context = context;
        this.poiInfos = poiInfos;
        this.locationLatLng = locationLatLng;
    }

    public LatLng getLocationLatLng() {
        return locationLatLng;
    }

    public void setLocationLatLng(LatLng locationLatLng) {
        this.locationLatLng = locationLatLng;
    }

    @Override
    public int getCount() {
        return poiInfos == null?0:poiInfos.size();
    }

    @Override
    public Object getItem(int position) {
        return poiInfos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_location_search_poi, null);
            vh = new ViewHolder(convertView);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        PoiInfo poiInfo = poiInfos.get(position);

        vh.tvName.setText(poiInfo.name);
        vh.tvAddress.setText(poiInfo.address);
        double distance = DistanceUtil.getDistance(locationLatLng, poiInfo.location);
        String s = "";

        if (distance > 100){
            double v = distance / 1000;
            String format = String.format("%.2f", v);
            if (format.endsWith(".00")){
                s= (int)v +"km";
            }else if (format.endsWith("0")){
                s= String.format("%.1f", v) +"km";
            }else {
                s= format +"km";
            }

        }else if (distance > 0){
            s = (int)distance + "m";
        }

        vh.tvDistance.setText(s);
        return convertView;
    }

    class ViewHolder {
        TextView tvName;
        TextView tvAddress;
        TextView tvDistance;


        ViewHolder(View view) {
            tvName = (TextView) view.findViewById(R.id.tv_name);
            tvAddress = (TextView) view.findViewById(R.id.tv_address);
            tvDistance = (TextView) view.findViewById(R.id.tv_distance);
        }
    }
}
